/**
 * 自定义loader
 * 将i18包裹的中文文案，转换成英文的key
 */
const path = require('path');
const reg = /i18next\.t\(\n*\s*["|']([\s\S]+?)["|']\n*\s*\)/g;
const regChar = /[*|:|.]/g;
const baseDir = process.cwd();
const fileName = path.join(baseDir + '/locale/lang/langKey.json');
const langKeyObj = require(fileName);

function replaceI18nextStr(template, context) {
  const res = template.match(reg);
  context = context || langKeyObj;
  if (res && res.length && Object.keys(context).length > 0) {
    res.map((str) => {
      let strNew = str;
      const strOrg = str;
      const key = str.replace(reg, `$1`).replace(regChar, '#');
      for (let langKey in context) {
        if (context[langKey] == key) {
          strNew = `i18next.t("${langKey}")`;
        }
      }
      template = template.replace(strOrg, strNew, 'g');

      return strNew;
    });
  }
  return template;
}
module.exports = replaceI18nextStr;
